# -*- coding: utf-8 -*-

import logging
import paramiko


class SshClient(object):
    def __init__(self, ip, username, password, port=22):
        self.ip = ip
        self.username = username
        self.password = password
        self.port = port
        self.client = paramiko.SSHClient()
        self.connect = None

    def __enter__(self):
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.client.connect(hostname=self.ip, port=self.port, username=self.username, password=self.password)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.client.close()

    def exec_cmd(self, cmd):
        try:
            stdin, stdout, stderr = self.client.exec_command(cmd)
        except Exception as e:
            logging.error(f"An error occurred when executing command {cmd} on {self.ip}: {e}")
            return '', ''
        return stdout.read().decode('utf-8'), stderr.read().decode('utf-8')